package com.banciyuan.bcywebview.biz.main.mineinfo.mark;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.detail.noveldetail.NovelIndexActivity;
import com.banciyuan.bcywebview.biz.main.discover.topwork.NovelTopWorkActivity;
import com.banciyuan.bcywebview.biz.main.discover.topwork.TopWorkActivity;
import com.banciyuan.bcywebview.biz.main.mineinfo.MySeries.WorkSeriesAdapter;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.SeriesItem;

/**
 * Created by squall on 2016/1/21.
 */
public class MyWorkSeriesFragment extends BaseLazyContainerFragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    private PullToRefreshListView refreshListView;
    private ListView mListView;
    private RequestQueue mQueue;
    private List<SeriesItem> seriesItems = new ArrayList<SeriesItem>();
    private WorkSeriesAdapter mAdapter;
    private int page = 1;
    private boolean loading = false;
    private boolean needClearAdapter = false;
    private boolean hasMore = true;
    private LoadingHelper mProgressbarHelper;
    private View mProgressbarView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View viewroot = inflater.inflate(R.layout.myworkseries_layout, null);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initAction();
        return viewroot;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initProgressbar(View viewroot) {
        mProgressbarView = viewroot.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new LoadingHelper(viewroot);
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
        viewroot.findViewById(R.id.tv_desc_two).setOnClickListener(this);
    }

    @Override
    protected void initUi(View viewroot) {
        viewroot.findViewById(R.id.base_title).setVisibility(View.GONE);
        refreshListView = (PullToRefreshListView) viewroot.findViewById(R.id.lv);
        mListView = refreshListView.getRefreshableView();
    }

    @Override
    protected void initAction() {
        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && hasMore) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!loading) {
                    hasMore = true;
                    loading = true;
                    page = 1;
                    needClearAdapter = true;
                    initData();
                }
            }
        });
        mListView.setOnItemClickListener(this);
    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    JSONObject result = null;
                    try {
                        result = new JSONObject(response);
                        Gson gson = new Gson();
                        List<SeriesItem> tempList = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<SeriesItem>>() {
                        }.getType());
                        if (tempList.size() == 0) {
                            hasMore = false;
                            if (page == 1)
                                mProgressbarHelper.onNodata("", true);
                        } else {
                            processData(tempList);
                            mProgressbarHelper.onSuccess();
                        }
                        loading = false;
                        refreshListView.onRefreshComplete();
                    } catch (JSONException e) {
                        e.printStackTrace();
                        loading = false;
                        refreshListView.onRefreshComplete();
                        mProgressbarHelper.onFailed();
                    }
                } else {
                    loading = false;
                    refreshListView.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressbarHelper.onFailed();
                loading = false;
                refreshListView.onRefreshComplete();
            }
        };
        String url = HttpUtils.BASE_URL + SpaceApi.getFocusednovelset();
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSuccess, url, getActivity(), null);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, params, onSuccess, errorProxy);
        mQueue.add(getUserdataRequest);
    }

    private void processData(List<SeriesItem> tempList) {
        if (null == mAdapter || needClearAdapter) {
            needClearAdapter = false;
            seriesItems = tempList;
            mAdapter = new WorkSeriesAdapter(getActivity(), seriesItems);
            mListView.setAdapter(mAdapter);
        } else {
            seriesItems.addAll(tempList);
            mAdapter.setdata(seriesItems);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        position = position - 1;
        if (position < 0 || position >= seriesItems.size())
            return;
        SeriesItem seriesItem = seriesItems.get(position);
        if (!TextUtils.isEmpty(seriesItem.getWns_id())) {
            gotoUtil.gotoAct(getActivity(), NovelIndexActivity.class, seriesItem.getWns_id());
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_desc_two:
                gotoUtil.gotoAct(getActivity(), NovelTopWorkActivity.class, TopWorkActivity.NOVEL_TYPE,"lastday");
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            page = 1;
            needClearAdapter = true;
            initData();
        }
    }
}
